<?php

namespace App\Http\Controllers\Api;

use App\ApiResponse;
use App\Http\Controllers\Controller;
use App\Http\Resources\MoneyLogRescource;
use App\Models\Fund;
use App\Models\MoneyLog;
use Illuminate\Http\Request;


class FundController extends Controller
{
    use ApiResponse;

    public function buy(Request $request)
    {
        $num = $request->input('num', 0);
        if ($num <= 0) {
            return $this->message("购买数量必须大于0", [], 400);
        } else {

            /** @var \App\Models\User $user */
            $user = $request->user('api');
//            dd($user);
            $insert['user_id'] = $user->id;
            $insert['num'] = $num;
            $insert['price'] = 10000;
            $insert['status'] = false;
            $insert['year'] = $request->input('year', 1);
            $insert['order_no'] = "F" . date('YmdHis') . rand(1000, 9999);
            $fund = Fund::create($insert);

            return $this->message('申请成功');
        }
    }

    public function fund(Request $request)
    {
        /** @var \App\Models\User $user */
        $user = $request->user('api');
        $funds = Fund::whereUserId($user->id)->orderBy('created_at', 'desc')->paginate();
        return $this->message('获取成功', $funds->items());
    }

    public function month(Request $request)
    {
        /** @var \App\Models\User $user */
        $user = $request->user('api');
        $fund = Fund::whereId($request->id)->first();
        $logs = MoneyLog::whereUserId($user->id)->where('type', 'fund_month')->where('order_no',$fund->order_no)->orderBy('created_at', 'desc')->paginate();
        return $this->message('获取成功', MoneyLogRescource::collection($logs));
    }

    public function logs(Request $request)
    {
        $logs = MoneyLog::whereUserId($request->user('api')->id)->where('type', 'fund')->orderBy('created_at', 'desc')->paginate();
        return $this->message('获取成功', MoneyLogRescource::collection($logs));
    }
}
